package clock.socoolby.com.clock.screen;

import android.accessibilityservice.AccessibilityService;
import android.os.Build;
import android.view.accessibility.AccessibilityEvent;

import timber.log.Timber;

public class LockAccessibilityService extends AccessibilityService {
    public static final String LOCK_COMMAND="Lock Screen";

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        Timber.v("onAccessibilityEvent(): "+event.getText().toString());
        if(null!=event) {
            if (event.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED && !event.getText().isEmpty()&&event.getText().get(0).toString().equalsIgnoreCase(LOCK_COMMAND)) {
                Timber.d("Received Lock Command");
                lockDevice();
            }
        }
    }

    private void lockDevice() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            Timber.d("Locking device using AccessibilityService");
            performGlobalAction(GLOBAL_ACTION_LOCK_SCREEN);
        } else {
            // This should never be reached, but we'll log it just in case.
            Timber.e("Locking device using AccessibilityService is only available for Android versions >= Pie");
        }
    }


    @Override
    public void onInterrupt() {
        Timber.v("onInterrupt()");
    }
}
